// Fill out your copyright notice in the Description page of Project Settings.

#include "Isalong2.h"
#include "DynamicTreeBase.h"
#include "DynamicTreePartBase.h"




UDynamicTreePartBase::UDynamicTreePartBase()
{
	BodyInstance.bAutoWeld = false;
	//SetCollisionProfileName(TEXT("BlockAll"));
}

void UDynamicTreePartBase::SetUpPart(UDynamicTreePartBase* upPart)
{
	_upPart = upPart;
	upPart->_downPart = this;
	upPart->AttachTo(this);
}

void UDynamicTreePartBase::SetDownPart(UDynamicTreePartBase* downPart)
{
	_downPart = downPart;
	downPart->_upPart = this;
	this->AttachTo(downPart);
}

void UDynamicTreePartBase::NodeHurtCheck(FVector hitLocation, int hurtType, float hurtValue)
{
	if (_lifeValue<0)
	{
		return;
	}
	_lifeValue -= hurtValue*3;
	if (_lifeValue <= 0 && _owner != nullptr)
	{	
		if (_downPart != nullptr)
		{
			_downPart->_upPart = nullptr;
		}
		_downPart = nullptr;

		// unweld all childs
		UnWeldAllChilds();
		_owner->OnPartBreak(this);
		SetSimulatePhysics(true);
		// weld all childs
		if (_upPart!=nullptr)
		{
			_upPart->WeldAllChilds();
		}

		SetCollisionProfileName(TEXT("NoPawnPhy"));
	}
}

void UDynamicTreePartBase::SetPartOwner(ADynamicTreeBase* owner)
{
	_owner = owner;
}

void UDynamicTreePartBase::UnWeldAllChilds()
{
	this->UnWeldFromParent();
	if (_upPart!=nullptr)
	{
		_upPart->UnWeldAllChilds();
	}
}

void UDynamicTreePartBase::WeldAllChilds()
{
	if (_downPart!=nullptr)
	{
		WeldTo(_downPart);
	}
	if (_upPart!=nullptr)
	{
		_upPart->WeldAllChilds();
	}
}

float UDynamicTreePartBase::GetWidth()
{
	return Bounds.BoxExtent.X * 2;
}

float UDynamicTreePartBase::GetHeight()
{
	return Bounds.BoxExtent.Z * 2;
}

float UDynamicTreePartBase::GetDepth()
{
	return Bounds.BoxExtent.Y * 2;
}

void UDynamicTreePartBase::SnapUp()
{

	if (_downPart!=nullptr)
	{
		this->SetRelativeLocation(FVector(0, 0, _downPart->GetHeight()/2 + GetHeight()/2 ));
	}
	else
	{
		this->SetRelativeLocation(FVector(0, 0, GetHeight() / 2));
	}
	if (_upPart!=nullptr)
	{
		_upPart->SnapUp();
	}
}